package com.joinlabs.yilong.web.servlet;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 验证码Servlet
 */
@WebServlet("/verification")
public class VerificationCodeServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		//服务器通知浏览器不要缓存
		response.setHeader("paragma", "no-cache");
		response.setHeader("cache-controll", "no-cache");
		response.setHeader("expores", "0");
		
		//在内存中创建图片
		//param1:长
		//param2:宽
		//param3:颜色  #009688
		int width = 80;
		int height = 30;
		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
		
		//获取画笔
		Graphics g = image.getGraphics();
		//设置画笔颜色
		g.setColor(new Color(00,96,88));
		//填充图片
		g.fillRect(0,0, width,height);
		
		//生产4个随机验证码
		String verificationCode = getCheckCode();
		//将验证码放入到HTTPSession中
		request.getSession().setAttribute("VERIFICATION_SERVER", verificationCode);
		
		//设置画笔颜色
		g.setColor(Color.YELLOW);
		//设置字体
		g.setFont(new Font("黑体", Font.BOLD, 24));
		//往图片中写入验证码
		g.drawString(verificationCode, 15, 25);
		
		//将内存中的图片输出到浏览器
		/*
		 * param1 图片对象
		 * param2 图片格式
		 * param3 图片输出流
		 */
		ImageIO.write(image, "PNG", response.getOutputStream());
	}
	
	private String getCheckCode() {
		String base = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
		int size = base.length();
		Random r = new Random();
		StringBuffer sb = new StringBuffer();
		for(int i=0; i<4;i++) {
			//生产0~size-1 的随机数
			int index = r.nextInt(size);
			//从base中截取一个字符
			char c = base.charAt(index);
			//将截取的字符放入到StringBuffere中
			sb.append(c);
		}
		return sb.toString();
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doGet(request, response);
	}

}
